package com.teamwork.module03.service.impl;

import com.alibaba.fastjson.JSON;
import com.teamwork.module03.security.LoginUser;
import com.teamwork.module03.service.LoginService;
import com.teamwork.common.constant.RedisConsts;
import com.teamwork.common.entity.common.User;
import com.teamwork.common.result.Result;
import com.teamwork.common.util.JwtUtil;
import com.teamwork.common.util.RedisUtil;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public Result login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        //使用userid生成token
        Object obj =  authenticate.getPrincipal();
        LoginUser loginUser = JSON.parseObject(JSON.toJSONString(obj), LoginUser.class);


        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
        redisUtil.set(RedisConsts.LOGIN_PRE+userId,loginUser);
        //把token响应给前端
        HashMap<String,String> map = new HashMap<>();
        map.put("token",jwt);
        //把用户信息返回去，存入store中
        map.put("userinfo",JSON.toJSONString(loginUser));
        return  Result.success(200,"登陆成功",map);
    }

    //注销
    @Override
    public Result logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();
        redisUtil.del(RedisConsts.LOGIN_PRE+userid);
        return  Result.success("退出成功！");
    }


}


